var config = require('../../common/config');
var utils = require('../../common').utils;
var request = require('request');
var global = require('../../common/global');
var _ = require('underscore');

var reqTemplate = config.reqTemplate;
var logger = config.logger('app');

exports.rentCarPage = function (req, res) {
    res.render('rent.hbs', {server_url : process.env.NODE_SERVER});
};

exports.travelPage = function (req, res) {
    res.render('travel.hbs', {server_url : process.env.NODE_SERVER});
};

exports.airportPage = function (req, res) {
    res.render('airport.hbs', {server_url : process.env.NODE_SERVER});
};

exports.generateRentOrder = function (req, res) {
    var user = utils.generateCookie(req.headers.cookie);

    if (!user || !user.uuId) {
        res.send({redirect: '/user/login'});
    } else {
        var userQuery = new reqTemplate("user/" + user.userId, "GET");
        userQuery.headers.authorization = user.uuId;
        request(userQuery, function (err, raw_user) {
            var whole_user = JSON.parse(raw_user.body);

            var order = eval('(' + req.body.order + ')');
            var order_obj = {
                status: "DEFINE",
                user_id: user.userId,
                customer_tel : whole_user.mobile,
                customer_name : whole_user.real_name ?
                    whole_user.real_name : whole_user.nick_name ?
                    whole_user.nick_name : whole_user.username
            };
            order_obj = _.extend(order_obj, order);

            var option = new reqTemplate("order_list");
            option.form = order_obj;
            option.headers.authorization = user.uuId;

            request(option, function (err, response) {
                if (err) {
                    logger.error(err.stack);
                    res.send(response || err);
                } else {
                    var order = eval("(" + response.body + ")");
                    global.orders[order.id] = order;

                    //todo handout by req_car_type
                    global.handOutOrder(order.id);
                    res.send(order);
                }
            });
        });
    }
};

exports.cancelOrder = function (req, res) {
    global.orders[req.body.id] && (delete global.orders[req.body.id]);
    var option = new reqTemplate('order_list/' + req.body.id, "PUT");
    option.form = {status: "CANCEL"};
    request(option, function (err, response) {
        !err ? res.send("success") : console.log(err);
    });
};